package cn.tedu.boot12.controller;

import cn.tedu.boot12.entity.User;
import cn.tedu.boot12.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.*;

/**
 * @Classname: UserController
 * @Author: bromide
 * @CreateTime: 2022/5/11--10:40
 * @Version: V1.0
 * @Description:
 */
@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user){
        try(Connection conn = DBUtils.getConn()) {
            PreparedStatement ps = conn.prepareStatement("select id from user where username=?");
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                //如果有下一个,则说明用户存在
                return "<h1>用户已存在!请重新<a href=\"/reg.html\">注册</a><h1>";
            }
            ps = conn.prepareStatement("insert into user values(null,?,?,?)");
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNickname());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "<h1>注册成功!!!!!!!!!!!!!!<h1>";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(User user){
        try(Connection conn = DBUtils.getConn()) {
            PreparedStatement ps = conn.prepareStatement("select password from user where username=?");
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                //如果有下一个    说明用户名存在
                if (rs.getString("password").equals(user.getPassword())){
                    return "<h1>登录成功!</h1>";
                }
                return "<h1>密码错误,请重新<a href=\"/login.html\">登录</a></h1>";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "<h1>用户名不存在,请重新<a href=\"/login.html\">登录</a></h1>";
    }
}
